import {
  useClipboard,
} from '@vueuse/core'
import { ElMessage } from 'element-plus'

export const vCopy = {
  name: 'copy',

  mounted(el: HTMLElement & { _vCopyClickHandler: () => void }, binding: any) {
    const clickHandler = () => {
      const { copy, isSupported } = useClipboard()
      if (isSupported) {
        copy(binding.value)
        ElMessage.success('复制成功！')
      }
      else {
        ElMessage.error('复制失败！')
      }
    }
    el.addEventListener('click', clickHandler)
    el._vCopyClickHandler = clickHandler
  },

  beforeUnmount(el: HTMLElement & { _vCopyClickHandler: () => void }) {
    if (el._vCopyClickHandler) {
      el.removeEventListener('click', el._vCopyClickHandler)
    }
  },
}
